<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :selected-keys="selectedKeys"
        @menu-item-click="doMenuClick"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
          <div class="title-bar">
            <img class="logo" src="../assets/oj-logo.svg" />
            <div class="title">eddy OJ</div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>
    <a-col flex="100px">
      <div>
        {{ store.state.user?.loginUser?.userName }}
      </div>
    </a-col>
  </a-row>
</template>

<script lang="ts" setup>
import { routes } from "@/router/routes";
import { useRouter } from "vue-router";
import { computed, ref } from "vue";
import { useStore } from "vuex";
import checkAccess from "@/access/checkAccess";

const router = useRouter();

const selectedKeys = ref(["/"]);

// 路由跳转后，更新选中的菜单项
//首先点击菜单项 => 触发点击事件，跳转更新路由 => 更新路由后，同步去更新菜单栏的高亮状态。
router.afterEach((to, from, failure) => {
  selectedKeys.value = [to.path];
});

const doMenuClick = (key: string) => {
  router.push({
    path: key,
  });
  // console.log(key);
};

//使用 user store 使用dispatch 方法调用
const store = useStore();
// console.log(store.state.user?.loginUser);

// setTimeout(() => {
//   store.dispatch("user/getLoginUser", {
//     userName: "eddy",
//     userRole: "admin",
//   });
// }, 3000);

// 过滤 routes 只显示要显示的view
// const visibleRoutes = routes.filter((item, index) => {
//   if (item.meta?.hideInMenu) {
//     return false;
//   }
//   return true;
// });
/**
 * 使用 computed 是为了用户登录的使用，userRole 发生改变了，能重新赋值给 visibleRoutes 进而改变视图
 */
const visibleRoutes = computed(() => {
  return routes.filter((item, index) => {
    if (item.meta?.hideInMenu) {
      return false;
    }

    if (
      !checkAccess(store.state.user.loginUser, item?.meta?.access as string)
    ) {
      return false;
    }
    return true;
  });
});
</script>

<style scoped>
/**
  display: flex;        弹性盒子
  align-items: center;  弹性盒子(字体居中)
 */
.title-bar {
  display: flex;
  align-items: center;
}

/**
  color: #444;        颜色
  margin-left: 16px;  外边距 marign-left
 */
.title {
  color: #444;
  margin-left: 16px;
}

/**
  height 高度
 */
.logo {
  height: 48px;
}
</style>
